package com.runen.wnhz.runen.ui.fragment.minem;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetStateUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.MyEvaluationBean;
import com.runen.wnhz.runen.data.entity.MyQuestionBean;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.presenter.Contart.EvaluationContart;
import com.runen.wnhz.runen.presenter.Contart.QuestionBankContart;
import com.runen.wnhz.runen.presenter.iPresenter.IEvaluationPersenter;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.MyTestAdapter;
import com.runen.wnhz.runen.ui.adapter.puadapter.MyTestListAdapter;
import com.runen.wnhz.runen.ui.fragment.BaseFragment;
import com.runen.wnhz.runen.widget.TitleBuilder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018-04-12.
 */

public class MyTestRecordListFragment extends BaseFragment<IEvaluationPersenter> implements QuestionBankContart.View, View.OnClickListener {

    @BindView(R.id.rv_message)
    RecyclerView recyclerView;

    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;

    private int page = 0;

    private UserBean reqeustUser;

    private MyTestListAdapter myTestListAdapter;

    private boolean hasNextPage = false;

    private int currentPage = 0;

    private int totalPage = 0;

    private boolean isRefresh = false;

    private boolean isLoadMore = false;

    private List<MyQuestionBean.DataBean.ListBean> listBeanList;

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {
  /*      DaggerCourseComponent.builder().applicationComponent(appComponent)
                .courseModule(new VModule(this))
                .build().initject(this);*/
    }

    private void getLearningLessonData(String pageNum) {
        if (getToken() != null) {
            FormBody formBody = new FormBody.Builder().add("token", getToken()).add("page", pageNum).build();
            Request request = new Request.Builder().url(NetUtils.TEST_MYTest).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                            refreshOrLoadMoreFailed();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleUserLesson(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("数据请求出现异常");
                                refreshOrLoadMoreFailed();
                            }
                        });
                    }
                }
            });
        }
    }

    private void refreshOrLoadMoreFailed() {
        if (isLoadMore) {
            smartRefreshLayout.finishLoadMore(false);
            isLoadMore = false;
        }
        if (isRefresh) {
            smartRefreshLayout.finishRefresh(false);
            isRefresh = false;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(getUserVisibleHint() && getActivity() != null){
            getLearningLessonData(String.valueOf(currentPage));
        }
    }

    private void handleUserLesson(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                final String json = responseBody.string();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyQuestionBean evaluationEntity = new Gson().fromJson(json, MyQuestionBean.class);
                        if (evaluationEntity != null) {
                            if ("1".equals( evaluationEntity.getRe())) {
                                MyQuestionBean.DataBean dataBean = evaluationEntity.getData();
                                totalPage = Integer.parseInt(dataBean.getSum_page());
                                currentPage = Integer.parseInt(dataBean.getSum_page());
                                String isPage = dataBean.getIs_page();
                                hasNextPage = "1".equals(isPage);
                                List<MyQuestionBean.DataBean.ListBean> list = evaluationEntity.getData().getList();
                                if (isRefresh) {
                                    if (list.size() != 0) {
                                        currentPage = 0;
                                    }
                                    if (listBeanList.size() != 0) {
                                        listBeanList.clear();
                                    }
                                    listBeanList.addAll(list);
                                    if (myTestListAdapter == null) {
                                        myTestListAdapter = new MyTestListAdapter(listBeanList, getContext());
                                        recyclerView.setAdapter(myTestListAdapter);
                                    } else {
                                        myTestListAdapter.notifyDataSetChanged();
                                    }
                                    isRefresh = false;
                                    smartRefreshLayout.finishRefresh(true);
                                    return;
                                }
                                if (isLoadMore) {
                                    if (list.size() != 0) {
                                        currentPage = currentPage + 1;
                                    }
                                    listBeanList.addAll(list);
                                    if (myTestListAdapter == null) {
                                        myTestListAdapter = new MyTestListAdapter(listBeanList, getContext());
                                        recyclerView.setAdapter(myTestListAdapter);
                                    } else {
                                        myTestListAdapter.notifyDataSetChanged();
                                    }
                                    isLoadMore = false;
                                    smartRefreshLayout.finishLoadMore(true);
                                    return;
                                }
                                currentPage = 0;
                                if(listBeanList.size() != 0){
                                    listBeanList.clear();
                                }
                                listBeanList.addAll(list);
                                myTestListAdapter = new MyTestListAdapter(listBeanList, getContext());
                                recyclerView.setAdapter(myTestListAdapter);
                            } else if ("0".equals(evaluationEntity.getRe())) {
                                ToastUtil.showToast(evaluationEntity.getInfo());
                            } else if ("-1".equals(evaluationEntity.getRe())) {
                                ToastUtil.showToast(evaluationEntity.getInfo());
                                startActivity(new Intent(getActivity(), LoginForPersonalActivity.class));
                            }
                        }
                    }
                });

            }
        }
    }


    private void setListener() {
        smartRefreshLayout.setEnableAutoLoadMore(false);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (NetStateUtils.isNetworkAvalible(getActivity())) {
                    if (hasNextPage) {
                        int tempCurrentPage = currentPage + 1;
                        isLoadMore = true;
                        getLearningLessonData(String.valueOf(tempCurrentPage));
                    } else {
                        ToastUtil.showToast("暂无更多数据");
                        smartRefreshLayout.finishLoadMore(true);
                    }
                } else {
                    ToastUtil.showToast("暂无网络");
                    smartRefreshLayout.finishLoadMore(false);
                }

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (NetStateUtils.isNetworkAvalible(getActivity())) {
                    int tempCurrentPage = 0;
                    isRefresh = true;
                    getLearningLessonData(String.valueOf(tempCurrentPage));
                } else {
                    ToastUtil.showToast("暂无网络");
                    smartRefreshLayout.finishRefresh(false);
                }
            }
        });
    }

    @Override
    protected int getLayoutView() {
        return R.layout.learning_fragment_layout;
    }

    @Override
    public void initUiAndListener(View view) {
        reqeustUser = ACacheUtlis.getInstance().getReqeustUser(getContext());
        listBeanList = new ArrayList<>();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListener();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        setUserVisibleHint(true);
    }

    @Override
    public void onStart() {
        super.onStart();
//        mPresenter.getContent();
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        setToolBarVisible(View.GONE);
    }

    @Override
    public void showLoadding() {

    }

    @Override
    public void dimissLoding() {

    }

    @Override
    public void showErrorMessage(String msg) {
//        ToastUtil.showToast(msg);
    }


    @Override
    public void onTitleButtonClicked(TitleBuilder.TitleButton clicked) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    @Override
    public String getPage() {
        return "0";
    }

    @Override
    public String getToken() {
        return reqeustUser.getToken();
    }

    @Override
    public void onSuccess(MyQuestionBean data) {
        myTestListAdapter = new MyTestListAdapter(data.getData().getList(),getContext());
    }


    //    @Override
    public void showLoginError(String info) {
        ToastUtil.showToast(info);
    }

    @Override
    public void onTokenError(String msg) {
        super.onTokenError(msg);
        startActivity(new Intent(getActivity(), LoginForPersonalActivity.class));
    }
/*
    @Override
    public void onSuccess(MyQuestionBean data) {

        myTestListAdapter = new MyTestListAdapter(data.getData().getList(),getContext());
//
//        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//
//        recyclerView.setAdapter(courseAdapter);
    }*/

}
